using Serilog;

namespace FServer.API.Extensions;

public static class WebApplicationExtensions
{
    public static WebApplication UseApiPipeline(this WebApplication app)
    {
        // 开发环境特殊配置
        if (app.Environment.IsDevelopment())
        {
            app.UseSwagger();
            app.UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint("/swagger/v1/swagger.json", "FServer API v1");
                c.RoutePrefix = string.Empty; // 设置 Swagger UI 为根路径
            });
        }

        // 添加请求日志
        app.UseSerilogRequestLogging(options =>
        {
            options.MessageTemplate = "HTTP {RequestMethod} {RequestPath} responded {StatusCode} in {Elapsed:0.0000} ms";
            options.GetLevel = (httpContext, elapsed, ex) => Serilog.Events.LogEventLevel.Information;
        });

        // 添加 CORS
        app.UseCors("AllowAll");

        // 添加路由
        app.UseRouting();

        // 添加认证和授权
        app.UseAuthentication();
        app.UseAuthorization();

        // 添加端点
        app.MapControllers();
        app.MapHealthChecks("/health");

        // 添加根路径重定向到 Swagger
        app.MapGet("/", () => Results.Redirect("/swagger"));

        return app;
    }
}
